package com.loongtech.bi.action.biflow;

import com.loongtech.bi.action.Base2BiSearchAction;
import com.loongtech.bi.manager.flow.HadoopQueryManager;
import com.loongtech.bi.manager.system.BiPlatformManager;
import com.loongtech.bi.manager.system.GameParamConfigManager;
import com.loongtech.bi.support.CommonGameParam;
import com.loongtech.core.util.Time;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.Map.Entry;

/**
 * 
 * ClassName: FightValueChangeNewAction
 * 
 * @description: 实时战力变动原因流水
 * @author yuri
 * @date 2017-7-1 下午4:32:27
 */
@Controller
@Scope("prototype")
@RequestMapping("/flow/fightValueChangeFlow")
public class FightValueChangeNewAction extends Base2BiSearchAction {
	private static final long serialVersionUID = 1L;
	@Resource
	HadoopQueryManager hadoopQueryManager;

	@RequestMapping(value = "updateServer.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updateServer(HttpServletRequest request, HttpServletResponse response, String serverid, String callback) {
		try {
			queryServer = serverid;
			selectServerItems();
			Map<String, Object> result = new HashMap<>();
			result.put("res", "0");
			result.put("channelItmes", channelItmes);
			result.put("platformItmes", platformItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
        }
	}

	@RequestMapping(value = "updateChannel.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updateChannel(HttpServletRequest request, HttpServletResponse response, String channelid,
			String callback) {
		try {
			queryChannel = channelid;
			selectChannelItems();
			Map<String, Object> result = new HashMap<>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("platformItmes", platformItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
        }
	}

	@RequestMapping(value = "updatePlatform.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updatePlatform(HttpServletRequest request, HttpServletResponse response, String platformid,
			String callback) {
		try {
			queryPlatform = platformid;
			selectPlatformItems();
			Map<String, Object> result = new HashMap<>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("channelItmes", channelItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
        }
	}

	@RequestMapping(value = "initParam.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void initParam(HttpServletRequest request, HttpServletResponse response, String callback) {
		try {
			Map<String, Object> result = new HashMap<>();
			result.put("res", "0");
			result.put("serverItmes", serverItmes);
			result.put("channelItmes", channelItmes);
			result.put("platformItmes", platformItmes);
			result.put("fightChangeList", GameParamConfigManager.getItems(CommonGameParam.FightValueChange_TYPE));
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
        }
	}

	@RequestMapping(value = "search.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam String params,
			String callback) {
		Map<String, Object> result = new HashMap<>();
		try {
			Map<String, Object> m = jsonToMap(params);
			Date dateStart = Time.formatDate((String) m.get("dateStart"), "yyyy-MM-dd");
			Date dateEnd = Time.formatDate((String) m.get("dateEnd"), "yyyy-MM-dd");

			String userid = (String) m.get("userid");
			String roleid = (String) m.get("roleid");

			String platform = (String) m.get("platform");
			String channel = (String) m.get("channel");
			String serverid = (String) m.get("serverid");

			String changeType = (String) m.get("changeType");
			// 开始结束时间不能大于当前时间60天
			if (Time.getInterval(new Date(), dateStart) > 60 || Time.getInterval(new Date(), dateEnd) > 60) {
				result.put("res", "1");
				result.put("msg", "开始结束时间不能小于当前时间60天!");
				printToJson(response, result, callback);
				return;
			}

			if (Time.getInterval(dateStart, dateEnd) < 0) {
				result.put("res", "1");
				result.put("msg", "开始时间不能大于结束时间!");
				printToJson(response, result, callback);
				return;
			}

			// 用户ID，角色ID必要有一个非空
			if (StringUtils.isBlank(userid) && StringUtils.isBlank(roleid)) {
				result.put("res", "1");
				result.put("msg", "用户ID，角色ID必须至少有一个非空!");
				printToJson(response, result, callback);
				return;
			}

			if (HadoopQueryManager.VISIT_QUEUE.offer("FightValueChangeNewAction")) {
				System.out.println("VISIT_QUEUE offer FightValueChangeNewAction ok!");

				StringBuilder sql = new StringBuilder();
				sql.append("select logtime,platform,channel,serverid,userid,roleid,rolelevel,type,tid,action,cur_fightingcapacity - old_fightingcapacity ,old_fightingcapacity, cur_fightingcapacity from fightingcapacity  where 1=1");
				if (!StringUtils.isBlank(userid)) {
					sql.append(" and userid = '");
					sql.append(userid.trim());
					sql.append("' ");
				}
				if (!StringUtils.isBlank(roleid)) {
					sql.append(" and roleid = '");
					sql.append(roleid.trim());
					sql.append("' ");
				}
				if (!"0".equals(platform)) {
					sql.append(" and platform = ");
					sql.append(platform);
				}
				if (!"0".equals(channel)) {
					sql.append(" and channel = '");
					sql.append(channel);
					sql.append("' ");
				}
				if (!"0".equals(serverid)) {
					sql.append(" and serverid = ");
					sql.append(serverid);
				}
				if (!StringUtils.isBlank(changeType) && Integer.parseInt(changeType) != -99999) {
					sql.append(" and type = '");
					sql.append(changeType.trim());
					sql.append("' ");
				}
				sql.append(" and dt >= '");
				sql.append(Time.getDateStr(dateStart));
				sql.append("' and dt <= '");
				sql.append(Time.getDateStr(dateEnd));
				sql.append("' ");
				sql.append(" order by logtime desc ");
				System.out.println(sql);
				Entry<List<String>, List<Object[]>> ret = hadoopQueryManager.executeSQL(sql.toString());
				if (null == ret || null == ret.getKey() || ret.getKey().isEmpty() || null == ret.getValue()
						|| ret.getValue().size() <= 0) {
                    result.put("res", new ArrayList<Object[]>());
                    result.put("data", "");
                    printToJson(response, result, callback);
					return;
				}
				List<Object[]> lo = ret.getValue();

				for (Object[] o : lo) {
					o[1] = BiPlatformManager.getPlatformNameById((String) o[1]);
					o[2] = BiPlatformManager.getChannelNameById((String) o[2]);
					o[3] = BiPlatformManager.getServerNameById((String) o[3]);
                    o[7] = fightValueChangeType(o[7]) + "(" + o[7] + ")";
                    o[8] = getItemType(o[8]);
                    o[9] = fightValueChangeAction(o[9]) + "(" + o[9] + ")";
				}

				result.put("res", "0");
				result.put("data", lo);
				printToJson(response, result, callback);
			} else {
				System.out.println("VISIT_QUEUE offer FightValueChangeNewAction failed!");
				result.put("res", "1");
				result.put("msg", "当前系统正被访问，为保证服务器稳定，请稍后再试!");
				printToJson(response, result, callback);
            }
		} catch (Exception e) {
			e.printStackTrace();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
		}
	}

	private Map<String, String> fightValueChangeActionItmesReverse = GameParamConfigManager.getItemsRevise(CommonGameParam.FightValueChange_ACTION); //  1.穿戴 2.卸下 3.过期 4.获得；

	private Map<String, String> fightValueChangeTypeListReverse = GameParamConfigManager
			.getItemsRevise(CommonGameParam.FightValueChange_TYPE); // 1：装备，2：称号，3：坐骑，4：主宠，5：助战宠，6：翅膀

    private Map<String, String> typeItmesReverse = GameParamConfigManager.getItemsRevise(CommonGameParam.ITEM_TYPE); // 物品类型反转

    // 查询物品名称
    public String getItemType(Object itemType) {
        String key = itemType == null ? "" : Math.abs(Integer.parseInt(itemType.toString())) + "";
        return (typeItmesReverse.get(key) == null) ? key : typeItmesReverse.get(key) + "(" + itemType + ")";
    }

	// 战力变化操作
    private String  fightValueChangeAction(Object itemType) {
		String key = itemType == null ? "" : Math.abs(Integer.parseInt(itemType.toString())) + "";
		return (fightValueChangeActionItmesReverse.get(key) == null) ? key : fightValueChangeActionItmesReverse.get(key) + "(" + itemType + ")";
	}

	// 战力变化类型
    private String fightValueChangeType(Object itemType) {
		String key = itemType == null ? "" : Math.abs(Integer.parseInt(itemType.toString())) + "";
		return (fightValueChangeTypeListReverse.get(key) == null) ? key : fightValueChangeTypeListReverse.get(key);
	}

	@Override
	public void search() {
		// TODO Auto-generated method stub

	}

	@Override
	protected String csvContent() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected String csvFileName() {
		// TODO Auto-generated method stub
		return null;
	}
}
